package com.wang.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sun.org.apache.bcel.internal.generic.NEW;
import com.wang.mapper.SyncMapper;
import com.wang.pojo.CustomerFeedback;
import com.wang.pojo.CustomerQuestion;
import com.wang.pojo.Sync;
import com.wang.response.PageResult;
import com.wang.response.Result;
import com.wang.response.ResultResponse;
import com.wang.service.CustomerQuestionService;
import com.wang.mapper.CustomerQuestionMapper;

import com.xxl.job.core.handler.annotation.XxlJob;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 *
 */
@Service
@Transactional
public class CustomerQuestionServiceImpl
    implements CustomerQuestionService{
    @Autowired
    CustomerQuestionMapper questionMapper;

    @Override
    public ResultResponse addQuestion(CustomerQuestion question) {
        if(question.getQuestionId()==null){
            questionMapper.insert(question);
            return ResultResponse.SUCCESS();
        }
        questionMapper.updateById(question);
        return ResultResponse.SUCCESS();
    }

    @Override
    public ResultResponse delQuestion(Integer questionId) {
        questionMapper.deleteById(questionId);
        return ResultResponse.SUCCESS();
    }

    @Override
    public ResultResponse queryQuestion(Map<String, Object> searchMap) {
        QueryWrapper<CustomerQuestion> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().orderByDesc(CustomerQuestion::getQcount).last("limit 20");
        List<CustomerQuestion> list = questionMapper.selectList(queryWrapper);
        return ResultResponse.SUCCESS(list);
    }


    @Override
    public PageResult<CustomerQuestion> searchQuestion(Integer pageNum, Integer pageSize, Map searchMap) throws IOException {
        SearchRequest searchRequest = new SearchRequest("healthquestion");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        Object keyword = searchMap.get("keyword");
        if(!StringUtils.isEmpty(keyword)){
            boolQueryBuilder.must(QueryBuilders.matchQuery("questionname",keyword));
        }
        searchSourceBuilder.query(boolQueryBuilder);
        searchSourceBuilder.from((pageNum-1)*pageSize);
        searchSourceBuilder.size(pageSize);
        HighlightBuilder highlightBuilder = new HighlightBuilder().field("questionname");
        highlightBuilder.preTags("<b style='color:red'>");
        highlightBuilder.postTags("</b>");
        searchSourceBuilder.highlighter(highlightBuilder);
        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        long value = searchResponse.getHits().getTotalHits().value;
        SearchHit[] hits = searchResponse.getHits().getHits();
        List<CustomerQuestion> questionList=new ArrayList<>();
        for (SearchHit hit : hits) {
            String sourceAsString = hit.getSourceAsString();
            CustomerQuestion question = JSON.parseObject(sourceAsString, CustomerQuestion.class);
            HighlightField highlightField = hit.getHighlightFields().get("questionname");
            if(null!=highlightField){
                Text[] fragments = highlightField.getFragments();
                question.setQuestionName(fragments[0].toString());
            }
            questionMapper.addQcount(question);
            questionList.add(question);
        }
        return new PageResult<CustomerQuestion>(value,questionList,200);
    }

    @Autowired
    SyncMapper syncMapper;
    @Autowired
    RestHighLevelClient restHighLevelClient;

    @Scheduled(cron = "0 0/10 * * * ?")
    public void syncData() throws IOException {
        Sync sync = syncMapper.selectById(1);
        QueryWrapper<CustomerQuestion> queryWrapper = new QueryWrapper<>();
        List<CustomerQuestion> list =null;
        if(sync.getSyncDate()==null){
            list = questionMapper.selectList(null);
        }else {
            queryWrapper.lambda().ge(CustomerQuestion::getCreateTime,sync.getSyncDate());
            list = questionMapper.selectList(queryWrapper);
        }
        if(list.size()>0){
            IndexRequest indexRequest = new IndexRequest("healthquestion");
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            for (CustomerQuestion question : list) {
                Map<String,Object> map=new HashMap<>();
                map.put("questionid",question.getQuestionId());
                map.put("questionname",question.getQuestionName());
                map.put("answer",question.getAnswer());
                map.put("delflag",question.getDelFlag());
                map.put("createtime",simpleDateFormat.format(question.getCreateTime()));
                map.put("updatetime",simpleDateFormat.format(question.getUpdateTime()));
                map.put("qcount",question.getQcount());
                indexRequest.id(question.getQuestionId()+"");
                indexRequest.source(map);
                restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
            }
        }
        sync.setSyncDate(new Date());
        syncMapper.updateById(sync);
    }

    @XxlJob("test1")
    public String test1(String param){
        System.out.println("执行成功");
        return param+"success";
    }


}




